package cn.fl.audit.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrQueryApiService;
import cmm.user.facade.system.dto.SysUsrDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.audit.condition.AudVisitRecordQueryCondition;
import cn.fl.audit.service.IAudVisitRecordService;
import cn.fl.audit.vo.AudVisitRecordVO;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.vo.CstBscInfoVO;
import cn.fl.customer.vo.CstCorpBscInfoVO;
import cn.fl.customer.vo.CstCorpTeamVO;
import cn.fl.customer.vo.CstNpBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.preloan.IAuditVisitRecordService;
import cn.fl.preloan.condition.AuditVisitRecordQueryCondition;
import cn.fl.preloan.dto.audit.*;
import cn.fl.project.condition.PrjCstBscInfoQueryCondition;
import cn.fl.project.condition.PrjLinkManQueryCondition;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.service.IPrjCstBscInfoService;
import cn.fl.project.service.IPrjLinkManService;
import cn.fl.project.vo.PrjCstBscInfoVO;
import cn.fl.project.vo.PrjLinkManVO;
import cn.fl.retvisit.dto.AudVisitRecordDTO;
import cn.fl.retvisit.service.IAudVisitRecordApiService;
import cn.fl.risk.constant.RiskConstant;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.fl.commons.result.ResponseData;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Description: 回访记录表 控制层
 */
@Controller
@RequestMapping("/audit/audVisitRecord")
public class AudVisitRecordController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(AudVisitRecordController.class);

	/**
	 * AudVisitRecord 服务层BEAN
	 */
	@Autowired
	private IAudVisitRecordService audVisitRecordService;
	
	/**
	 * 项目客户信息查询服务
	 */
	@Autowired
	private IPrjCstBscInfoService prjCstBscInfoService;
	
	/**
	 * 客户查询服务
	 */
	@Autowired
	private ICstBscInfoService cstBscInfoService;
	
	/**
	 *项目联系人服务
	 */
	@Autowired
	private IPrjLinkManService prjLinkManService;
	
	/**
     * 数据字典API服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    
    @Autowired
    private ISysUsrQueryApiService sysUsrQueryApiService;


	@Autowired
	private IAuditVisitRecordService auditVisitRecordService;

	/**
	 * 到后续回访记录列表页面
	 */
	@RequestMapping(value = "/toFlowVisitRecordListPage.do", method = { RequestMethod.GET})
	public ModelAndView toFlowVisitRecordListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("audit/audReturnVisit/audFlowReturnVisitList");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("audit/audVisitRecord/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String visitId = request.getParameter("visitId");//回访基本信息ID
		String visitTypeCd = request.getParameter("visitTypeCd");//回访类型
		//后续回访记录列表查询条件
		String personnelName = request.getParameter("personnelName");//回访人员姓名
		String accountManagerNm = request.getParameter("accountManagerNm");//客户经理
		String auditorNm = request.getParameter("auditorNm");//信审员
		String crtStartDt = request.getParameter("crtStartDt");//回访日期(起)
		String crtEndDt = request.getParameter("crtEndDt");//回访日期(止)
		String flag = request.getParameter("flag");//flag:1 后续回访记录列表
		try {
			Pager page = new Pager();
			if (StringUtils.isNotEmpty(currentPage)) {
				page.setCurrentPage(Integer.parseInt(currentPage));
			}

			if (StringUtils.isNotEmpty(pageSize)) {
				page.setEveryPage(Integer.parseInt(pageSize));
			}

			AudVisitRecordQueryCondition qc = new AudVisitRecordQueryCondition();
			if (StringUtils.isNotEmpty(visitId)) {
				qc.setVisitId(Long.valueOf(visitId));
			}else if(!"1".equals(flag)){
				return new ListPageVO<AudVisitRecordVO>(new ArrayList<AudVisitRecordVO>(), 0);
			}
			if(StringUtils.isNotEmpty(visitTypeCd)){
				qc.setVisitTypeCd(visitTypeCd);
			}
			if(StringUtils.isNotEmpty(personnelName)){
				qc.setPersonnelName(personnelName);
			}
			if(StringUtils.isNotEmpty(accountManagerNm)){
				qc.setAccountManagerNm(accountManagerNm);
			}
			if(StringUtils.isNotEmpty(auditorNm)){
				qc.setAuditorNm(auditorNm);
			}
			if(StringUtils.isNotEmpty(crtStartDt)){
				qc.setCrtStartDt(DateUtils.formatStringToDate(crtStartDt, DateUtils.YYYY_MM_DD));
			}
			if(StringUtils.isNotEmpty(crtEndDt)){
				qc.setCrtEndDt(DateUtils.formatStringToDate(crtEndDt, DateUtils.YYYY_MM_DD));
			}
			page.setCondition(qc);

			Pager pager = this.audVisitRecordService.searchListPage(page);
			List<AudVisitRecordVO> list = (List<AudVisitRecordVO>) pager.getResultList();
			ListPageVO<AudVisitRecordVO> listPage = new ListPageVO<AudVisitRecordVO>(list, pager.getTotalCount());
			BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
			return listPage;
		} catch (Exception e) {
			BaseLogUtils.info(logger, "initList", "查询数据异常. visitId:"+visitId, CurrentThreadContext.getCurrentUserName());
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 首次进入修改回访记录页面-初始化回访列表
	 * 自动带出担保人和紧急联系人信息-REQ-3024
	 */
	@RequestMapping(value = "/firstInitList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object firstInitList(HttpServletRequest request, HttpServletResponse response) {
		String prjId = request.getParameter("prjId");//项目Id
		String cstMgrId = request.getParameter("cstMgrId"); //客户经理ID
		String cstMgrNm = request.getParameter("cstMgrNm"); //客户经理名称
		String visitTypeCd = request.getParameter("visitTypeCd");//回访类型
		
		try {
			boolean isAudit = false;
			Long currentUserId = CurrentThreadContext.getCurrentUserId();
			String currentUserName = CurrentThreadContext.getCurrentUserName();
			//查数据字典-->评审人员角色ID
	        List<SysUsrDTO> auditUsrList = new ArrayList<SysUsrDTO>();
	        List<SysDictionaryDTO> dicList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), RiskConstant.CODE_COLLECTOR_ROLE_CD);
	        if (CollectionUtils.isNotEmpty(dicList)) {
	            SysDictionaryDTO sysDictionaryDTO = dicList.get(0);
	            if (null != sysDictionaryDTO) {
	                String roleIdString = sysDictionaryDTO.getCode();
	                if (StringUtils.isNotEmpty(roleIdString)) {
	                    auditUsrList = this.sysUsrQueryApiService.searchAuthSysUsrListByRoleId(Long.valueOf(roleIdString), CurrentThreadContext.getCurrentSysCd());//信审员集合
	                }
	            }
	        }
	        //判断当前用户是否为评审人员
	        if (CollectionUtils.isNotEmpty(auditUsrList) && StringUtils.isNotEmpty(currentUserId)) {
	            for (SysUsrDTO sysUsrDTO : auditUsrList) {
	                if(currentUserId.equals(sysUsrDTO.getId())){
	                	isAudit = true;
	                	break;
	                }
	            }
	        }
	        
			//初始化回访记录列表
			List<AudVisitRecordVO> audVisitList = new ArrayList<AudVisitRecordVO>();
			AudVisitRecordVO audVisitRecordVO = new AudVisitRecordVO();
			//第一步：获取担保人信息
			//1.根据项目ID查询对应的担保人ID
			PrjCstBscInfoQueryCondition prjCstBscInfoQc = new PrjCstBscInfoQueryCondition();
			if(StringUtils.isNotEmpty(prjId)){
				prjCstBscInfoQc.setPrjId(Long.valueOf(prjId));
				prjCstBscInfoQc.setCstRlTyp(PrjBscInfoConstant.CODE_CST_RL_SPONSOR); //担保人
			}
			List<PrjCstBscInfoVO> prjCstList = this.prjCstBscInfoService.searchList(prjCstBscInfoQc);
			//2.根据担保人ID查询对应的担保人信息（客户表）
			if(CollectionUtils.isNotEmpty(prjCstList)){
				for (PrjCstBscInfoVO prjCstBscInfoVO : prjCstList) {
					CstBscInfoVO cstBscInfoVO = this.cstBscInfoService.selectDetailById(prjCstBscInfoVO.getCstId());
					if(null != cstBscInfoVO){
						audVisitRecordVO = new AudVisitRecordVO();
						//获取回访电话
						if("1".equals(cstBscInfoVO.getCstTypCd())){ //自然人客户
							CstNpBscInfoVO cstNpBscInfoVO = cstBscInfoVO.getCstNpBscInfoVO();
							audVisitRecordVO.setPhone(cstNpBscInfoVO.getMp1());
						}else{//法人客户
							CstCorpBscInfoVO cstCorpBscInfoVO = cstBscInfoVO.getCstCorpBscInfoVO();
							if(null != cstCorpBscInfoVO){ //获取法人手机号
								CstCorpTeamVO cstCorpTeamVO = cstCorpBscInfoVO.getCstCorpTeamVO();
								audVisitRecordVO.setPhone(cstCorpTeamVO.getMp1());
							}
						}
						//设置基本信息
						audVisitRecordVO.setVisitTypeCd(visitTypeCd); //回访类型
						audVisitRecordVO.setPersonnelTypeCd(PrjBscInfoConstant.CODE_CST_RL_SPONSOR); //人员类型:2 担保人
						audVisitRecordVO.setPersonnelTypeCdNm("担保人");
						audVisitRecordVO.setPersonnelName(cstBscInfoVO.getCstNm()); //人员姓名
						if(StringUtils.isNotEmpty(cstMgrId)){ //客户经理ID
							audVisitRecordVO.setAccountManagerId(Long.valueOf(cstMgrId));
						}
						audVisitRecordVO.setAccountManagerNm(cstMgrNm); //客户经理
						if(isAudit){
							audVisitRecordVO.setAuditorId(currentUserId); //信审员：当前用户
							audVisitRecordVO.setAuditorNm(currentUserName);
						}
						audVisitRecordVO.setIsSelfAnswer(BaseConstant.IS_YESNO_YES); //是否本人接听：1 是
						audVisitRecordVO.setIsSelfAnswerNm("是");
						audVisitRecordVO.setIdentityCd("1"); //身份信息：1 一致
						audVisitRecordVO.setIdentityCdNm("一致");
						audVisitRecordVO.setAddressCd("1"); //家庭住址：1 一致
						audVisitRecordVO.setAddressCdNm("一致");
						audVisitRecordVO.setIsKnowInfo(BaseConstant.IS_YESNO_YES); //是否知晓承租人购车：1 是
						audVisitRecordVO.setIsKnowInfoNm("是");
						audVisitRecordVO.setIsHelpConact(BaseConstant.IS_YESNO_YES); //是否愿意协助我司联系/是否愿意承担连带责任：1 是
						audVisitRecordVO.setIsHelpConactNm("是");
						audVisitList.add(audVisitRecordVO);
					}
				}
			}
			//第二步：获取紧急联系人信息
			PrjLinkManQueryCondition prjLinkManQc = new PrjLinkManQueryCondition();
			if (StringUtils.isNotEmpty(prjId)) {
				prjLinkManQc.setPrjId(Long.valueOf(prjId));
			}
			List<PrjLinkManVO> prjLinkManList = this.prjLinkManService.searchList(prjLinkManQc);
			if(CollectionUtils.isNotEmpty(prjLinkManList)){
				for (PrjLinkManVO prjLinkManVO : prjLinkManList) {
					audVisitRecordVO = new AudVisitRecordVO();
					audVisitRecordVO.setPhone(prjLinkManVO.getMp()); //回访电话
					//设置基本信息
					audVisitRecordVO.setVisitTypeCd(visitTypeCd); //回访类型
					audVisitRecordVO.setPersonnelTypeCd("3"); //人员类型:3 紧急联系人
					audVisitRecordVO.setPersonnelTypeCdNm("紧急联系人");
					audVisitRecordVO.setPersonnelName(prjLinkManVO.getLnkNm()); //人员姓名
					if(StringUtils.isNotEmpty(cstMgrId)){ //客户经理ID
						audVisitRecordVO.setAccountManagerId(Long.valueOf(cstMgrId));
					}
					audVisitRecordVO.setAccountManagerNm(cstMgrNm); //客户经理
					if(isAudit){
						audVisitRecordVO.setAuditorId(currentUserId); //信审员：当前用户
						audVisitRecordVO.setAuditorNm(currentUserName);
					}
					audVisitRecordVO.setIsSelfAnswer(BaseConstant.IS_YESNO_YES); //是否本人接听：1 是
					audVisitRecordVO.setIsSelfAnswerNm("是");
					audVisitRecordVO.setIdentityCd("1"); //身份信息：1 一致
					audVisitRecordVO.setIdentityCdNm("一致");
					audVisitRecordVO.setAddressCd("1"); //家庭住址：1 一致
					audVisitRecordVO.setAddressCdNm("一致");
					audVisitRecordVO.setIsKnowInfo(BaseConstant.IS_YESNO_YES); //是否知晓承租人购车：1 是
					audVisitRecordVO.setIsKnowInfoNm("是");
					audVisitRecordVO.setIsHelpConact(BaseConstant.IS_YESNO_YES); //是否愿意协助我司联系/是否愿意承担连带责任：1 是
					audVisitRecordVO.setIsHelpConactNm("是");
					audVisitList.add(audVisitRecordVO);
				}
			}

			ListPageVO<AudVisitRecordVO> listPage = new ListPageVO<AudVisitRecordVO>(audVisitList, audVisitList.size());
			BaseLogUtils.info(logger, "firstInitList", "查询数据完成. DATA:" + JSONObject.toJSONString(audVisitList), CurrentThreadContext.getCurrentUserName());
			return listPage;
		} catch (Exception e) {
			BaseLogUtils.info(logger, "firstInitList", "查询数据异常. prjId:"+prjId, CurrentThreadContext.getCurrentUserName());
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(ids)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "removeMfrById", "删除回访记录数据,主键参数为空!ids:"+ids, CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		List<Long> idsList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.fromObject(ids);
		for (Object object : idsArray) {
			idsList.add(Long.valueOf(object.toString()));
		}
		
		try {
			RemoveAudVisitRecordRequest removeRequest = new RemoveAudVisitRecordRequest(idsList);
			ResponseData responseData = auditVisitRecordService.removeAudVisitRecordByIds(removeRequest);
			if (!ResponseData.SUCCESS_CODE.equals(responseData.getCode())) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+ids+"]", CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+ids+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			AudVisitRecordVO vo = this.audVisitRecordService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		List<AudVisitRecordVO> audVisitRecordVOList = null;
		try {
			audVisitRecordVOList = this.getRequestParamForAdd(request);
			if(CollectionUtils.isNotEmpty(audVisitRecordVOList)){
				for (AudVisitRecordVO audVisitRecordVO : audVisitRecordVOList) {
					audVisitRecordVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				}
			}
			Boolean success = this.audVisitRecordService.batchAdd(audVisitRecordVOList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_ADD_FAIL);
				BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(audVisitRecordVOList), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "add", "新增数据.DATA:" + JSONObject.toJSONString(audVisitRecordVOList), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(audVisitRecordVOList) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(audVisitRecordVOList) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	//********************私有方法********************//
	/**
	 * 获取参数信息
	 * @param request
	 * @return
	 * @throws BaseException
	 */
	private List<AudVisitRecordVO> getRequestParam(HttpServletRequest request)throws BaseException{
		List<AudVisitRecordVO> audVisitRecordVOList = new ArrayList<AudVisitRecordVO>();
		String visitId = request.getParameter("visitId");//回访信息ID
		String visitTypeCd = request.getParameter("visitTypeCd");//回访记录类型
		if(StringUtils.isEmpty(visitId)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "回访基本信息ID不能为空.");
		}
		if(StringUtils.isEmpty(visitTypeCd)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "回访记录类型不能为空.");
		}
		String VisitRecordDetailJSON = request.getParameter("VisitRecordDetailJSON");//回访记录集合JSON
		audVisitRecordVOList = JSON.parseArray(VisitRecordDetailJSON, AudVisitRecordVO.class);
		if(CollectionUtils.isEmpty(audVisitRecordVOList)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "回访记录不能为空,请添加回访记录.");
		}
		for (AudVisitRecordVO audVisitRecordVO : audVisitRecordVOList) {
			audVisitRecordVO.setVisitId(Long.valueOf(visitId));
			audVisitRecordVO.setVisitTypeCd(visitTypeCd);
		}
		return audVisitRecordVOList;
	}
	
	/**
	 * 获取请求参数(新增)
	 * @param request 请求
	 * @return 
	 */
	private List<AudVisitRecordVO> getRequestParamForAdd(HttpServletRequest request)throws BaseException{
		List<AudVisitRecordVO> audVisitRecordVOList = this.getRequestParam(request);
		if(CollectionUtils.isNotEmpty(audVisitRecordVOList)){
			long count = 1L;
			for (AudVisitRecordVO audVisitRecordVO : audVisitRecordVOList) {
				audVisitRecordVO.setTimes(count);
				if(audVisitRecordVO.getId()!=null){//修改
					audVisitRecordVO.setMdfTm(new Date());
					audVisitRecordVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				}else{//新增
					audVisitRecordVO.setCrtTm(new Date());
					audVisitRecordVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				}
				count++;
			}
		}
		return audVisitRecordVOList;
	}
	
	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initListPost.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initListPost(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String visitId = request.getParameter("visitId");//回访基本信息ID
		String visitTypeCd = request.getParameter("visitTypeCd");//回访类型
		//后续回访记录列表查询条件
		String personnelName = request.getParameter("personnelName");//回访人员姓名
		String accountManagerNm = request.getParameter("accountManagerNm");//客户经理
		String auditorNm = request.getParameter("auditorNm");//信审员
		String crtStartDt = request.getParameter("crtStartDt");//回访日期(起)
		String crtEndDt = request.getParameter("crtEndDt");//回访日期(止)
		String flag = request.getParameter("flag");//flag:1 后续回访记录列表
		try {
			Pager page = new Pager();
			if (StringUtils.isNotEmpty(currentPage)) {
				page.setCurrentPage(Integer.parseInt(currentPage));
			}

			if (StringUtils.isNotEmpty(pageSize)) {
				page.setEveryPage(Integer.parseInt(pageSize));
			}

			AudVisitRecordQueryCondition qc = new AudVisitRecordQueryCondition();
			if (StringUtils.isNotEmpty(visitId)) {
				qc.setVisitId(Long.valueOf(visitId));
			}else if(!"1".equals(flag)){
				return new ListPageVO<AudVisitRecordVO>(new ArrayList<AudVisitRecordVO>(), 0);
			}
			if(StringUtils.isNotEmpty(visitTypeCd)){
				qc.setVisitTypeCd(visitTypeCd);
			}
			if(StringUtils.isNotEmpty(personnelName)){
				qc.setPersonnelName(personnelName);
			}
			if(StringUtils.isNotEmpty(accountManagerNm)){
				qc.setAccountManagerNm(accountManagerNm);
			}
			if(StringUtils.isNotEmpty(auditorNm)){
				qc.setAuditorNm(auditorNm);
			}
			if(StringUtils.isNotEmpty(crtStartDt)){
				qc.setCrtStartDt(DateUtils.formatStringToDate(crtStartDt, DateUtils.YYYY_MM_DD));
			}
			if(StringUtils.isNotEmpty(crtEndDt)){
				qc.setCrtEndDt(DateUtils.formatStringToDate(crtEndDt, DateUtils.YYYY_MM_DD));
			}
			page.setCondition(qc);

			Pager pager = this.audVisitRecordService.searchListPage(page);
			List<AudVisitRecordVO> list = (List<AudVisitRecordVO>) pager.getResultList();
			ListPageVO<AudVisitRecordVO> listPage = new ListPageVO<AudVisitRecordVO>(list, pager.getTotalCount());
			BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
			return listPage;
		} catch (Exception e) {
			BaseLogUtils.info(logger, "initList", "查询数据异常. visitId:"+visitId, CurrentThreadContext.getCurrentUserName());
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIdsPost.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeByIdsPost(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(ids)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "removeMfrById", "删除回访记录数据,主键参数为空!ids:"+ids, CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		List<Long> idsList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.fromObject(ids);
		for (Object object : idsArray) {
			idsList.add(Long.valueOf(object.toString()));
		}
		
		try {
			boolean success = this.audVisitRecordService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+ids+"]", CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+ids+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initPageList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initPageList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String visitId = request.getParameter("visitId");//回访基本信息ID
		String visitTypeCd = request.getParameter("visitTypeCd");//回访类型
		//后续回访记录列表查询条件
		String personnelName = request.getParameter("personnelName");//回访人员姓名
		String accountManagerNm = request.getParameter("accountManagerNm");//客户经理
		String auditorNm = request.getParameter("auditorNm");//信审员
		String crtStartDt = request.getParameter("crtStartDt");//回访日期(起)
		String crtEndDt = request.getParameter("crtEndDt");//回访日期(止)
		String flag = request.getParameter("flag");//flag:1 后续回访记录列表
		try {
			Pager page = new Pager();
			if (StringUtils.isNotEmpty(currentPage)) {
				page.setCurrentPage(Integer.parseInt(currentPage));
			}

			if (StringUtils.isNotEmpty(pageSize)) {
				page.setEveryPage(Integer.parseInt(pageSize));
			}

			AuditVisitRecordQueryCondition qc = new AuditVisitRecordQueryCondition();
			if (StringUtils.isNotEmpty(visitId)) {
				qc.setVisitId(Long.valueOf(visitId));
			}else if(!"1".equals(flag)){
				return new ListPageVO<AudVisitRecordVO>(new ArrayList<AudVisitRecordVO>(), 0);
			}
			if(StringUtils.isNotEmpty(visitTypeCd)){
				qc.setVisitTypeCd(visitTypeCd);
			}
			if(StringUtils.isNotEmpty(personnelName)){
				qc.setPersonnelName(personnelName);
			}
			if(StringUtils.isNotEmpty(accountManagerNm)){
				qc.setAccountManagerNm(accountManagerNm);
			}
			if(StringUtils.isNotEmpty(auditorNm)){
				qc.setAuditorNm(auditorNm);
			}
			if(StringUtils.isNotEmpty(crtStartDt)){
				qc.setCrtStartDt(DateUtils.formatStringToDate(crtStartDt, DateUtils.YYYY_MM_DD));
			}
			if(StringUtils.isNotEmpty(crtEndDt)){
				qc.setCrtEndDt(DateUtils.formatStringToDate(crtEndDt, DateUtils.YYYY_MM_DD));
			}
			//回访人员姓名，全量查询
			if (StringUtils.isEmpty(personnelName) && StringUtils.isEmpty(crtStartDt)){
				//先判断
				Calendar instance = Calendar.getInstance();
				instance.setTime(new Date());
				instance.add(Calendar.YEAR, -1);
				instance.add(Calendar.DATE, 1);
				qc.setCrtStartDt(DateUtils.formatDate(instance.getTime(), DateUtils.YYYY_MM_DD));
			}
			//过滤掉贷后的数据
			qc.setNotDataInitSource("1");
			page.setCondition(qc);
			//组装请求参数
			AudVisitRecordPageRequest pageRequest = new AudVisitRecordPageRequest(qc, CurrentThreadContext.getCurrentSysCd()
					, CurrentThreadContext.getCurrentOrgCd(), page.getCurrentPage(), page.getEveryPage());
			ResponseData<AudVisitRecordPageResponseDTO> responseData = auditVisitRecordService.searchAudVisitRecordListPage(pageRequest);
			BaseLogUtils.info(logger, "initList", "searchAudVisitRecordListPage完成. DATA:" + JSONObject.toJSONString(responseData), CurrentThreadContext.getCurrentUserName());
			ListPageVO<AudVisitRecordVO> listPage = new ListPageVO<>();
			if (responseData != null && ResponseData.SUCCESS_CODE.equals(responseData.getCode()) && responseData.getData() != null) {
				List<AudVisitRecordVO> list = new ArrayList<>();
				List<AuditVisitRecordDTO> audVisitRecordDTOS = responseData.getData().getAudVisitRecordDTOS();
				for (AuditVisitRecordDTO dto : audVisitRecordDTOS) {
					AudVisitRecordVO vo = new AudVisitRecordVO();
					BeanUtils.copyProperties(dto, vo);
					vo.setAccountManagerNm(dto.getAccountManagerName());
					vo.setAuditorNm(dto.getAuditorName());
					vo.setLastAuditorNm(dto.getLastAuditorName());
					list.add(vo);
				}
				listPage = new ListPageVO<>(list, responseData.getData().getTotalCount());
			}
			BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(listPage), CurrentThreadContext.getCurrentUserName());
			return listPage;
		} catch (Exception e) {
			BaseLogUtils.info(logger, "initList", "查询数据异常. visitId:"+visitId, CurrentThreadContext.getCurrentUserName());
			e.printStackTrace();
		}
		return null;
	}
}

